<template>
  <div class="inline-container">
    <!-- :='$attrs'继承原生属性 -->
    <!-- v-model可以分解为：value:value和@input="xxx";v-model是语法糖 -->
    <template v-if="type === 'textarea'">
      <textarea
        :disabled="disabled"
        class="r-textarea"
        v-bind="$attrs"
        :value="value"
        @input="handleInput"
      />
    </template>
    <template v-else>
      <div class="inline-container" :class="className">
        <div class="r-input-prepend" v-if="this.$slots.prepend">
          <slot name='prepend'></slot>
        </div>
        <div class="r-input-outer">
          <input
            type="text"
            class="r-input"
            :class="styleClass"
            :disabled="disabled"
            v-bind="$attrs"
            :value="value"
            @input="handleInput"
             @change="handleChange"
          />
          <span class="r-input-clear" @click="clearText" v-if="showClear">
            <w-icon name="yiliao_danao"></w-icon>
          </span>
        </div>
          <div class="r-input-append" :class="className" v-if="this.$slots.append">
          <slot name='append'></slot>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
export default {
  name: "w-input",
  props: {
    value: {
      type: [String, Number],
    },
    type: {
      type: String,
      default: "text",
      validator: (value) => {
        return ["text", "textarea"].includes(value);
      },
    },
    size: {
      type: String,
      default: "",
      validator: (value) => {
        return ["medium", "small", ""].includes(value);
      },
    },
    clearable: {
      type: Boolean,
      default: false,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    center: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // val:this.value
    };
  },
  computed: {
    styleClass() {
      return {
        [`r-input--${this.size}`]: this.size,
        [`is-disabled`]: this.disabled,
        [`is-center`]: this.center,
      };
    },
    showClear() {
      return this.clearable && this.value;
    },
    className(){
      return {
        'has-prepend':this.$slots.prepend,
        'has-append':this.$slots.append
      }
    }
  },
  mounted() {},

  methods: {
    handleInput(event) {
      // 通过input标签的原生事件input将值emit出去，以达到值得改变实现双向绑定
      this.$emit("input", event.target.value);
    },
    clearText() {
      this.$emit("input", "");
    },
    handleChange(){
      this.$emit('change')
    }
  },
};
</script>

<style scoped>
@import "./input.css";
</style>